// +----------------------------------------------------------------------
// | EasyGoAdmin敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2019~2025 深圳EasyGoAdmin研发中心
// +----------------------------------------------------------------------
// | Licensed Apache-2.0 EasyGoAdmin并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.easygoadmin.vip
// +----------------------------------------------------------------------
// | Author: @半城风雨 团队荣誉出品 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package router

import (
	"easygoadmin/app/controller"
	middleware2 "easygoadmin/app/middleware"
	"easygoadmin/app/middleware/multitemplate"
	"easygoadmin/app/widget"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"html/template"
	"path/filepath"
	"strings"
	"time"
)

// 注册路由
func RegisterRouter(e *echo.Echo) {
	// 注册登录验证中间件
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	// 登录验证中间件
	e.Use(middleware2.CheckLogin)

	// 向echo实例注册模版引擎
	e.Renderer = LoadTemplates("views")

	// 设置静态资源URL前缀和目录
	e.Static("/static", "./public/static")
	e.Static("/favicon.ico", "./public/static/assets/images")

	/* 文件上传 */
	upload := e.Group("upload")
	{
		// 上传图片
		upload.POST("/uploadImage", controller.Upload.UploadImage)
		upload.POST("/uploadEditImage", controller.Upload.UploadEditImage)
	}

	/* 登录注册 */
	index := e.Group("")
	{
		index.GET("/", controller.Index.Index)
		index.Any("/login", controller.Login.Login)
		index.GET("/captcha", controller.Login.Captcha)
		index.GET("/index", controller.Index.Index)
		index.GET("/main", controller.Index.Main)
		index.Any("/userInfo", controller.Index.UserInfo)
		index.Any("/updatePwd", controller.Index.UpdatePwd)
		index.GET("/logout", controller.Index.Logout)
	}

	//router.GET("/logout", controller.Index.Logout)

	/* 用户管理 */
	user := e.Group("user")
	{
		user.GET("/index", controller.User.Index)
		user.POST("/list", controller.User.List)
		user.GET("/edit/:id", controller.User.Edit)
		user.POST("/add", controller.User.Add)
		user.POST("/update", controller.User.Update)
		user.POST("/delete/:id", controller.User.Delete)
		user.POST("/setStatus", controller.User.Status)
		user.POST("/resetPwd", controller.User.ResetPwd)
	}

	// 职级管理
	level := e.Group("/level")
	{
		level.GET("/index", controller.Level.Index)
		level.POST("/list", controller.Level.List)
		level.GET("/edit/:id", controller.Level.Edit)
		level.POST("/add", controller.Level.Add)
		level.POST("/update", controller.Level.Update)
		level.POST("/delete/:id", controller.Level.Delete)
		level.POST("/setStatus", controller.Level.Status)
		level.POST("/import", controller.Level.ImportExcel)
		level.POST("/export", controller.Level.ExportExcel)
	}

	/* 岗位管理 */
	position := e.Group("position")
	{
		position.GET("/index", controller.Position.Index)
		position.POST("/list", controller.Position.List)
		position.GET("/edit/:id", controller.Position.Edit)
		position.POST("/add", controller.Position.Add)
		position.POST("/update", controller.Position.Update)
		position.POST("/delete/:id", controller.Position.Delete)
		position.POST("/setStatus", controller.Position.Status)
	}

	/* 角色路由 */
	role := e.Group("role")
	{
		role.GET("/index", controller.Role.Index)
		role.POST("/list", controller.Role.List)
		role.GET("/edit/:id", controller.Role.Edit)
		role.POST("/add", controller.Role.Add)
		role.POST("/update", controller.Role.Update)
		role.POST("/delete/:id", controller.Role.Delete)
		role.POST("/setStatus", controller.Role.Status)
		role.GET("/getRoleList", controller.Role.GetRoleList)
	}

	/* 角色菜单权限 */
	roleMenu := e.Group("rolemenu")
	{
		roleMenu.GET("/index/:roleId", controller.RoleMenu.Index)
		roleMenu.POST("/save", controller.RoleMenu.Save)
	}

	/* 部门管理 */
	dept := e.Group("dept")
	{
		dept.GET("/index", controller.Dept.Index)
		dept.POST("/list", controller.Dept.List)
		dept.GET("/edit/:id", controller.Dept.Edit)
		dept.POST("/add", controller.Dept.Add)
		dept.POST("/update", controller.Dept.Update)
		dept.POST("/delete/:id", controller.Dept.Delete)
		dept.GET("/getDeptList", controller.Dept.GetDeptList)
	}

	/* 菜单管理 */
	menu := e.Group("menu")
	{
		menu.GET("/index", controller.Menu.Index)
		menu.POST("/list", controller.Menu.List)
		menu.GET("/edit/:id", controller.Menu.Edit)
		menu.POST("/add", controller.Menu.Add)
		menu.POST("/update", controller.Menu.Update)
		menu.POST("/delete/:id", controller.Menu.Delete)
	}

	///* 登录日志 */
	//loginLog := e.Group("loginlog")
	//{
	//	loginLog.GET("/index", controller.LoginLog.Index)
	//	loginLog.GET("/list", controller.LoginLog.List)
	//	loginLog.POST("/delete/:id", controller.LoginLog.Delete)
	//}
	//
	///* 操作日志 */
	//operLog := e.Group("operlog")
	//{
	//	operLog.GET("/list", controller.OperLog.List)
	//}

	/* 友链管理 */
	link := e.Group("link")
	{
		link.GET("/index", controller.Link.Index)
		link.POST("/list", controller.Link.List)
		link.GET("/edit/:id", controller.Link.Edit)
		link.POST("/add", controller.Link.Add)
		link.POST("/update", controller.Link.Update)
		link.POST("/delete/:id", controller.Link.Delete)
		link.POST("/setStatus", controller.Link.Status)
	}

	/* 城市管理 */
	city := e.Group("city")
	{
		city.GET("/index", controller.City.Index)
		city.POST("/list", controller.City.List)
		city.GET("/edit/:id", controller.City.Edit)
		city.POST("/add", controller.City.Add)
		city.POST("/update", controller.City.Update)
		city.POST("/delete/:id", controller.City.Delete)
		city.POST("/getChilds", controller.City.GetChilds)
	}

	/* 站点管理 */
	item := e.Group("item")
	{
		item.GET("/index", controller.Item.Index)
		item.POST("/list", controller.Item.List)
		item.GET("/edit/:id", controller.Item.Edit)
		item.POST("/add", controller.Item.Add)
		item.POST("/update", controller.Item.Update)
		item.POST("/delete/:id", controller.Item.Delete)
		item.POST("/setStatus", controller.Item.Status)
		item.GET("/getItemList", controller.Item.GetItemList)
	}

	/* 栏目管理 */
	itemcate := e.Group("itemcate")
	{
		itemcate.GET("/index", controller.ItemCate.Index)
		itemcate.POST("/list", controller.ItemCate.List)
		itemcate.GET("/edit/:id", controller.ItemCate.Edit)
		itemcate.POST("/add", controller.ItemCate.Add)
		itemcate.POST("/update", controller.ItemCate.Update)
		itemcate.POST("/delete/:id", controller.ItemCate.Delete)
		itemcate.GET("/getCateList", controller.ItemCate.GetCateList)
		itemcate.GET("/getCateTreeList", controller.ItemCate.GetCateTreeList)
	}

	/* 通知管理 */
	notice := e.Group("notice")
	{
		notice.GET("/index", controller.Notice.Index)
		notice.POST("/list", controller.Notice.List)
		notice.GET("/edit/:id", controller.Notice.Edit)
		notice.POST("/add", controller.Notice.Add)
		notice.POST("/update", controller.Notice.Update)
		notice.POST("/delete/:id", controller.Notice.Delete)
		notice.POST("/setStatus", controller.Notice.Status)
	}

	/* 会员等级 */
	memberlevel := e.Group("memberlevel")
	{
		memberlevel.GET("/index", controller.MemberLevel.Index)
		memberlevel.POST("/list", controller.MemberLevel.List)
		memberlevel.GET("/edit/:id", controller.MemberLevel.Edit)
		memberlevel.POST("/add", controller.MemberLevel.Add)
		memberlevel.POST("/update", controller.MemberLevel.Update)
		memberlevel.POST("/delete/:id", controller.MemberLevel.Delete)
		memberlevel.GET("/getMemberLevelList", controller.MemberLevel.GetMemberLevelList)
	}

	/* 会员管理 */
	member := e.Group("member")
	{
		member.GET("/index", controller.Member.Index)
		member.POST("/list", controller.Member.List)
		member.GET("/edit/:id", controller.Member.Edit)
		member.POST("/add", controller.Member.Add)
		member.POST("/update", controller.Member.Update)
		member.POST("/delete/:id", controller.Member.Delete)
		member.POST("/setStatus", controller.Member.Status)
	}

	/* 广告位管理 */
	adsort := e.Group("adsort")
	{
		adsort.GET("/index", controller.AdSort.Index)
		adsort.POST("/list", controller.AdSort.List)
		adsort.GET("/edit/:id", controller.AdSort.Edit)
		adsort.POST("/add", controller.AdSort.Add)
		adsort.POST("/update", controller.AdSort.Update)
		adsort.POST("/delete/:id", controller.AdSort.Delete)
		adsort.GET("/getAdSortList", controller.AdSort.GetAdSortList)
	}

	/* 广告管理 */
	ad := e.Group("ad")
	{
		ad.GET("/index", controller.Ad.Index)
		ad.POST("/list", controller.Ad.List)
		ad.GET("/edit/:id", controller.Ad.Edit)
		ad.POST("/add", controller.Ad.Add)
		ad.POST("/update", controller.Ad.Update)
		ad.POST("/delete/:id", controller.Ad.Delete)
		ad.POST("/setStatus", controller.Ad.Status)
	}

	/* 字典管理 */
	dict := e.Group("dict")
	{
		dict.GET("/index", controller.Dict.Index)
		dict.POST("/list", controller.Dict.List)
		dict.POST("/add", controller.Dict.Add)
		dict.POST("/update", controller.Dict.Update)
		dict.POST("/delete/:id", controller.Dict.Delete)
	}

	/* 字典项管理 */
	dictdata := e.Group("dictdata")
	{
		dictdata.POST("/list", controller.DictData.List)
		dictdata.POST("/add", controller.DictData.Add)
		dictdata.POST("/update", controller.DictData.Update)
		dictdata.POST("/delete/:id", controller.DictData.Delete)
	}

	/* 配置管理 */
	config := e.Group("config")
	{
		config.GET("/index", controller.Config.Index)
		config.POST("/list", controller.Config.List)
		config.POST("/add", controller.Config.Add)
		config.POST("/update", controller.Config.Update)
		config.POST("/delete/:id", controller.Config.Delete)
	}

	/* 配置项管理 */
	configdata := e.Group("configdata")
	{
		configdata.POST("/list", controller.ConfigData.List)
		configdata.POST("/add", controller.ConfigData.Add)
		configdata.POST("/update", controller.ConfigData.Update)
		configdata.POST("/delete/:id", controller.ConfigData.Delete)
		configdata.POST("/setStatus", controller.ConfigData.Status)
	}

	/* 网站设置 */
	configweb := e.Group("configweb")
	{
		configweb.Any("/index", controller.ConfigWeb.Index)
	}

	/* 统计分析 */
	analysis := e.Group("analysis")
	{
		analysis.GET("/index", controller.Analysis.Index)
	}

	/* 代码生成器 */
	generate := e.Group("generate")
	{
		generate.GET("/index", controller.Generate.Index)
		generate.POST("/list", controller.Generate.List)
		generate.POST("/generate", controller.Generate.Generate)
		generate.POST("/batchGenerate", controller.Generate.BatchGenerate)
	}

	/* 演示一 */
	example := e.Group("example")
	{
		example.GET("/index", controller.Example.Index)
		example.POST("/list", controller.Example.List)
		example.GET("/edit/:id", controller.Example.Edit)
		example.POST("/add", controller.Example.Add)
		example.POST("/update", controller.Example.Update)
		example.POST("/delete/:id", controller.Example.Delete)
		example.POST("/setStatus", controller.Example.Status)
		example.POST("/setIsVip", controller.Example.IsVip)
	}

	/* 演示二 */
	example2 := e.Group("example2")
	{
		example2.GET("/index", controller.Example2.Index)
		example2.POST("/list", controller.Example2.List)
		example2.GET("/edit/:id", controller.Example2.Edit)
		example2.POST("/add", controller.Example2.Add)
		example2.POST("/update", controller.Example2.Update)
		example2.POST("/delete/:id", controller.Example2.Delete)
		example2.POST("/setStatus", controller.Example2.Status)
	}

	/* 文章 */
	article := e.Group("article")
	{
		article.GET("/index", controller.Article.Index)
		article.POST("/list", controller.Article.List)
		article.GET("/edit/:id", controller.Article.Edit)
		article.POST("/add", controller.Article.Add)
		article.POST("/update", controller.Article.Update)
		article.POST("/delete/:id", controller.Article.Delete)
		article.POST("/setIsTop", controller.Article.IsTop)
		article.POST("/setStatus", controller.Article.Status)
	}
}

func LoadTemplates(templatesDir string) echo.Renderer {
	r := multitemplate.New()

	// 非模板嵌套
	htmls, err := filepath.Glob(templatesDir + "/*.html")
	if err != nil {
		panic(err.Error())
	}
	for _, html := range htmls {
		r.AddFromGlob(filepath.Base(html), html)
	}

	// 布局模板
	layouts, err := filepath.Glob(templatesDir + "/layouts/*.html")
	if err != nil {
		panic(err.Error())
	}

	// 嵌套的内容模板
	includes, err := filepath.Glob(templatesDir + "/includes/**/*.html")
	if err != nil {
		panic(err.Error())
	}

	// template自定义函数
	funcMap := template.FuncMap{
		"StringToLower": func(str string) string {
			return strings.ToLower(str)
		},
		"date2": func() string {
			return time.Now().Format("2006-01-02 15:04:05.00000")
		},
		"safe": func(str string) template.HTML {
			return template.HTML(str)
		},
		"widget":       widget.Widget,
		"query":        widget.Query,
		"add":          widget.Add,
		"edit":         widget.Edit,
		"delete":       widget.Delete,
		"dall":         widget.Dall,
		"expand":       widget.Expand,
		"collapse":     widget.Collapse,
		"addz":         widget.Addz,
		"switch":       widget.Switch,
		"select":       widget.Select,
		"submit":       widget.Submit,
		"icon":         widget.Icon,
		"transfer":     widget.Transfer,
		"upload_image": widget.UploadImage,
		"album":        widget.Album,
		"item":         widget.Item,
		"kindeditor":   widget.Kindeditor,
		"date":         widget.Date,
		"checkbox":     widget.Checkbox,
		"radio":        widget.Radio,
		"city":         widget.City,
		"import":       widget.Import,
		"export":       widget.Export,
	}

	// 将主模板，include页面，layout子模板组合成一个完整的html页面
	for _, include := range includes {
		// 文件名称
		baseName := filepath.Base(include)
		files := []string{}
		if strings.Contains(baseName, "edit") {
			files = append(files, templatesDir+"/layouts/form.html", include)
		} else if strings.Contains(baseName, "dict") {
			files = append(files, templatesDir+"/layouts/main.html", include)
			// 字典
			dict, _ := filepath.Glob(templatesDir + "/includes/dict/*.html")
			files = append(files, dict...)
		} else if strings.Contains(baseName, "config") && !strings.Contains(baseName, "configweb") {
			files = append(files, templatesDir+"/layouts/main.html", include)
			// 配置
			dict, _ := filepath.Glob(templatesDir + "/includes/config/*.html")
			files = append(files, dict...)
		} else if strings.Contains(baseName, "user_info") {
			files = append(files, include)
		} else {
			files = append(files, templatesDir+"/layouts/layout.html", include)
		}
		files = append(files, layouts...)
		r.AddFromFilesFuncs(baseName, funcMap, files...)
	}
	return &r
}
